package org.dev.vlp.controller;

import org.dev.vlp.bean.JsonResponse;
import org.dev.vlp.constants.Roles;
import org.dev.vlp.constants.SearchType;
import org.dev.vlp.entity.Book;
import org.dev.vlp.entity.Statistics;
import org.dev.vlp.exception.ApiException;
import org.dev.vlp.interceptor.RequiredPermission;
import org.dev.vlp.service.BookService;
import org.dev.vlp.service.StatisticsService;
import org.dev.vlp.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description
 * Param
 * return
 * Author:86184
 * Date: 2023/1/15
 */
@RestController
@RequestMapping("/learn/book")
@RequiredPermission({Roles.ROLE_USER})
public class LearnBookController extends BaseController {


    @Autowired
    private WordService wordService;

    @Autowired
    private BookService bookService;

    @GetMapping
    public JsonResponse<Object> getBookList() {
        List<Book> list = bookService.getBookList((int)getUid());
        Map<String, Object> map = new HashMap<>();
        map.put("bookList", list);
        return JsonResponse.success(map);
    }

    @GetMapping("/word/search")
    public JsonResponse<Object> search(Integer page, Integer size, String keyWord, Integer type, Long bookId) {
        if (size == null || page == null || page < 0 || size < 0 || type == null) {
            throw new ApiException("参数错误");
        }
        if (keyWord == null) {
            throw new ApiException("关键词不能为空");
        }
        if (!type.equals(SearchType.ALL) && !type.equals(SearchType.IN_BOOK)) {
            throw new ApiException("检索类型参数错误");
        }
        return JsonResponse.success(wordService.search(page, size, type, getUid(), keyWord, bookId));
    }

    @GetMapping("/{id}")
    public JsonResponse<Object> bookDetail(@PathVariable Long id) {
        Book book = bookService.getBookDetail(id,(int)getUid());
        HashMap<String, Object> res = new HashMap<>();
        res.put("book", book);
        return JsonResponse.success(res);
    }


    @PutMapping
    public JsonResponse<Statistics> choiceBook(@RequestParam int bookId) {
        Statistics statistics = bookService.choiceBook(getUid(), bookId);
        return JsonResponse.success(statistics);
    }


    @GetMapping("/word/{id}")
    public JsonResponse<Object> word(Integer page, Integer size, @PathVariable Long id) {
        return JsonResponse.success(wordService.getBookWordPage(id, page, size,getUid()));
    }
}
